﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Approval;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Approval
{
    public class GetDepartMentHeadCommandHandler : IRequestHandler<GetDepartMentHeadCommand, APIResult<List<User>>>
    {
        private readonly IBaseRepository<User> userRep;

        public GetDepartMentHeadCommandHandler(IBaseRepository<User> userRep)
        {
            this.userRep = userRep;
        }

        public async Task<APIResult<List<User>>> Handle(GetDepartMentHeadCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<User>>();

            // 根据当前用户角色确定要查询的上级角色
            int targetHeadId = request.DepartmentHeadId switch
            {
                0 => 1,   // 员工查部门领导
                1 => 2,   // 部门领导查总裁
                _ => -1    // 其他情况不查询
            };

            if (targetHeadId == -1)
            {
                result.Code = APIEnum.查询成功;
                result.Msg = "当前角色无上级领导";
                result.data = new List<User>();
                return result;
            }

            // 构建查询条件
            var query = userRep.GetAll().Result;

            // 部门领导需要同部门，总裁不需要部门限制
            if (targetHeadId == 1)
            {
                query = query.Where(x => x.DepId == request.depId && x.DepartmentHeadId == targetHeadId);
            }
            else
            {
                query = query.Where(x => x.DepartmentHeadId == targetHeadId);
            }

            var list = query.ToList();

            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = list;
            return await Task.FromResult(result);
        }
    }
}

